# @Time   : 2022/7/26 14:37
# @Author : Fioman
# @Phone  : 13149920693
# @Tips   : Talk is Cheap,Show me the code! ^_^^_^
import socket
# addr = ("192.168.0.12", 9000)

# clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# ret = clientSocket.connect(addr)
# print("ret: {}".format(ret))
# res = clientSocket.recv(1024)
# print("res: {}".format(res))

# clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# # 开启保活机制
# clientSocket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True)
# clientSocket.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 120 * 1000, 30 * 1000))
# ret = clientSocket.connect(addr)
# print("ret: {}".format(ret))
# res = clientSocket.recv(1024)
# print("res: {}".format(res))



import socket
from tools.hd_logger import HdLogger
import gevent
from db_tools.db_handler import DbHandler
from app.states import DeviceStates
import threading

ds = DeviceStates()

#
class MyServer(object):
    def __init__(self):
        self.client_socket = None
        # 创建一个TCP/IP套接字
        self.socketService = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 绑定服务器地址和端口
        self.logger = HdLogger()
        self.cameraGroupStates = False
        self.server_address = ("192.168.0.3", 11258)
        # self.click_address = ("192.168.0.12", 9000)
        # 创建socket服务器
        self.socketService.bind(self.server_address)
        # 开始监听连接
        self.socketService.listen(5)
        print('通讯服务正在运行，等待接收信息...')
        self.logger.debug("通讯服务正在运行，等待接收信息...")
        # self.Handler()
        # while True:
        #     gevent.sleep(0.5)
        #     continue
        self.handlerThread = threading.Thread(target=self.Handler, name="handlerThread")
        # print('通讯服务正在运行，等待接收信息...')
        # self.logger.debug("通讯服务正在运行，等待接收信息...")

    def Handler(self):
        while True:
            # 等待新的客户端连接
            self.client_socket, client_address = self.socketService.accept()
            print('服务器正在运行，等待客户端连接...')
            try:
                print('客户端已连接:', client_address)
                self.cameraGroupStates = True
                # if
                while True:
                    # 接收客户端发送的数据
                    data = self.client_socket.recv(1024)
                    sendData = "620.29,300.61,-84.8195,\r\n"
                    if data:
                        # 处理接收到的数据
                        print('接收到来自客户端的数据:{}'.format(data))
                        self.logger.debug(data)
                        gevent.sleep(1)
                        self.client_socket.send(sendData.encode("gbk"))
                    else:
                        # 客户端断开连接
                        print('客户端已断开连接:', client_address)
                        break
            except Exception as e:
                print(e)
                gevent.sleep(1)
                continue
            finally:
                # 关闭客户端连接
                self.client_socket.close()
                break
    #
    # def Handler(self):
    #     while True:
    #         try:
    #             self.socketService.connect(self.click_address)
    #             self.cameraGroupStates = True
    #             while self.cameraGroupStates:
    #                 try:
    #                     data = self.socketService.recv(1024)
    #                     print("连接服务器成功！")
    #                 except Exception as e:
    #                     self.cameraGroupStates = False
    #                     print(e)
    #                     continue
    #                 if len(data) > 0:
    #                     # 处理接收到的数据
    #                     print('接收到来自服务器的数据:{}'.format(data))
    #                     self.logger.debug(data)
    #                     self.pares_msg(data)
    #                     gevent.sleep(1)
    #                 else:
    #                     # 客户端断开连接
    #                     print('已与服务器断开连接:', data)
    #                     self.cameraGroupStates = False
    #                     continue
    #             gevent.sleep(0.5)
    #             continue
    #         except Exception as e:
    #             # print("Handler", e)
    #             gevent.sleep(1)
    #             self.socketService.close()
    #             continue

# 定义发送的数据
sendData = "-450.340,-599.450,55.560, 0, 0, 0\r\n"

if __name__ == '__main__':
    myServer = MyServer()
    myServer.Handler()
# for i in range(1):
#     clientSocket.send(sendData.encode("gbk"))
